package gw;

import gw.utilidades.Imagenes;
import gw.utilidades.Utilidades;
import java.awt.AWTException;
import java.awt.Image;
import java.awt.SystemTray;
import java.awt.TrayIcon;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.util.Timer;
import javax.swing.ImageIcon;
import javax.swing.JMenuItem;
import javax.swing.JPopupMenu;

/**
 *
 * @author jcastillo
 */
public class SystemTraySwing implements ActionListener, MouseListener {

    private JPopupMenu popup = new JPopupMenu();
    private TrayIcon trayIcon;
    private FrmVentana frmVentana;
    private Timer timer;

    public SystemTraySwing(FrmVentana frmVentana) {
        this.frmVentana = frmVentana;
        this.timer = new Timer();

    }

    public void activar() {
        if (SystemTray.isSupported()) {
            SystemTray systemTray = SystemTray.getSystemTray();
            Image icoTray = Imagenes.get(Imagenes.NO_DEFINIDO_24).getImage();
            ImageIcon icoSalir = Imagenes.get(Imagenes.NO_DEFINIDO_24);
            JMenuItem mnuSalir = new JMenuItem("Salir del sistema", icoSalir);
            mnuSalir.addActionListener(this);
            mnuSalir.addMouseListener(this);
            popup.add(mnuSalir);
            trayIcon = new TrayIcon(icoTray, "Doble clic para mostrar la pantalla principal", null);
            trayIcon.setImageAutoSize(true);
            trayIcon.addActionListener(this);
            trayIcon.addMouseListener(this);
            try {
                systemTray.add(trayIcon);
            } catch (AWTException ex) {
                Utilidades.sop("No es posible agregar el System Tray al sistema");
            }
        } else {
            Utilidades.sop("El sistema no soporte el System Tray");
        }
    }

    public void MostrarMensaje(String mensaje) {
        trayIcon.displayMessage("Alerta...", mensaje, TrayIcon.MessageType.INFO);
    }

    public void actionPerformed(ActionEvent me) {
        Object obj = me.getSource();
        if (obj instanceof JMenuItem) {
            Utilidades.sop("Good Bye System.");
            System.exit(1);
        } else if (obj instanceof TrayIcon) {
            frmVentana.setVisible(true);
            frmVentana.toFront();
        }
    }

    public void mouseReleased(MouseEvent me) {
        //if (me.isPopupTrigger()) {
        if (me.getButton() == MouseEvent.BUTTON3) {
            popup.setLocation(me.getX(), me.getY());
            popup.setInvoker(popup);
            popup.setVisible(true);
            //timer.schedule(null, 0, 2 * 100);
            
        }
    }

    public void mouseClicked(MouseEvent me) {
    }

    public void mousePressed(MouseEvent me) {
    }

    public void mouseEntered(MouseEvent me) {
    }

    public void mouseExited(MouseEvent me) {
        Object obj = me.getSource();
        if (obj instanceof JMenuItem) {
            popup.setVisible(false);
        }
    }
}